package com.company.project.rocketmq.processor;

import java.math.BigDecimal;

import javax.annotation.Resource;

import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.company.project.constant.TradeEnums;
import com.company.project.protocol.mq.CancelOrderMQ;
import com.company.project.protocol.user.ChangeUserMoneyReq;
import com.company.project.rocketmq.IMessageProcessor;
import com.company.project.service.TradeUserService;

/**
 * 用户模块 处理 取消订单的 处理逻辑 一般指定 一个 groupName : user_ace_trade_cancel_group
 */
@Component
public class UserCancelOrderProcessor implements IMessageProcessor {
	public static final Logger LOGGER = LoggerFactory.getLogger(UserCancelOrderProcessor.class);
	@Resource
	private TradeUserService userService;

	public boolean handleMessage(MessageExt messageExt) {
		try {
			String body = new String(messageExt.getBody(), "UTF-8");
			String msgId = messageExt.getMsgId();
			String tags = messageExt.getTags();
			String keys = messageExt.getKeys();
			LOGGER.info("UserCancelOrderProcessor receive message:" + body);
			CancelOrderMQ cancelOrderMQ = JSON.parseObject(body, CancelOrderMQ.class);

			if (cancelOrderMQ.getUserMoney() != null && cancelOrderMQ.getUserMoney().compareTo(BigDecimal.ZERO) == 1) {
				ChangeUserMoneyReq changeUserMoneyReq = new ChangeUserMoneyReq();
				changeUserMoneyReq.setUserId(cancelOrderMQ.getUserId());
				changeUserMoneyReq.setMoneyLogType(TradeEnums.UserMoneyLogTypeEnum.REFUND.getCode());
				changeUserMoneyReq.setOrderId(cancelOrderMQ.getOrderId());
				changeUserMoneyReq.setUserMoney(cancelOrderMQ.getUserMoney());
				userService.changeUserMoney(changeUserMoneyReq);// 需要幂等处理 业务去重
			}
			return true;
		} catch (Exception e) {
			return false;
		}

	}

}
